<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="分类名称">
        <el-input
          v-model="queryParams['sysType.typeName']"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品价格" prop="goodsPrice">
        <el-input
          v-model="queryParams.goodsPrice"
          placeholder="请输入商品价格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品状态" prop="goodsStatus">
        <el-select v-model="queryParams.goodsStatus" placeholder="请选择商品状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_goods_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['mysystem:goods:add']"
        >新增</el-button>
      </el-col>-->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['mysystem:goods:edit']"
        >修改</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDeleteList"
          v-hasPermi="['mysystem:goods:remove']"
        >取消收藏</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mysystem:goods:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      :default-sort="{prop: 'createTime', order: 'descending'}"
      v-loading="loading"
      :data="goodsList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="分类名称" align="center" prop="sysType.typeName" />
      <el-table-column label="商品名称" align="center" prop="goodsName" />
      <!-- <el-table-column label="商品描述" align="center" prop="goodDescription" /> -->
      <el-table-column label="商品价格" align="center" prop="goodsPrice" />
      <el-table-column label="商品图片" align="center" prop="picture" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.picture" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center" prop="goodsStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_goods_status" :value="scope.row.goodsStatus" />
        </template>
      </el-table-column>
      <el-table-column :sortable="true" label="发布时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-search"
            @click="handleLookGoodsDetails(scope.row)"
            v-hasPermi="['mysystem:goods:remove']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['mysystem:goods:remove']"
          >取消收藏</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="typeId">
          <el-select v-model="form.typeId" placeholder="请选择商品分类">
            <el-option
              v-for="item in typeList"
              :key="item.typeId"
              :label="item.typeName"
              :value="item.typeId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品描述" prop="goodDescription">
          <el-input v-model="form.goodDescription" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="商品价格" prop="goodsPrice">
          <el-input v-model="form.goodsPrice" placeholder="请输入商品价格" />
        </el-form-item>
        <el-form-item label="商品图片" prop="picture">
          <image-upload v-model="form.picture" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoodsCollections,
  getGoods,
  delGoods,
  addGoods,
  updateGoods
} from "@/api/mysystem/goods";
import { listType } from "@/api/mysystem/type";
import { cancelCollection,cancelCollectionList } from "@/api/mysystem/collection";

export default {
  name: "releasedList",
  dicts: ["sys_goods_status"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      //商品类型列表
      typeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 备注时间范围
      daterangeUpdataTime: [],
      // 查询参数
      queryParams: {
        userId: null, //用户ID
        pageNum: 1,
        pageSize: 10,
        typeId: null,
        "sysType.typeName": null,
        goodsName: null,
        goodDescription: null,
        goodsPrice: null,
        goodsStatus: null,
        createBy: null,
        createTime: null,
        updataBy: null,
        updataTime: null,
        remark: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.getList();
  },
  methods: {
    // 处理查看收藏商品详情按钮
    handleLookGoodsDetails(row) {
      this.$router.push({
        path: "/main/goodsDetails",
        query: { goodsId: row.goodsId }
      });
    },

    /**查询所有分类列表 */
    getTypeList() {
      listType().then(response => {
        this.typeList = response.rows;
      });
    },
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      this.getTypeList();
      // this.queryParams.params = {};
      // if (null != this.daterangeCreateTime && "" != this.daterangeCreateTime) {
      //   this.queryParams.params[
      //     "beginCreateTime"
      //   ] = this.daterangeCreateTime[0];
      //   this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      // }
      // if (null != this.daterangeUpdataTime && "" != this.daterangeUpdataTime) {
      //   this.queryParams.params[
      //     "beginUpdataTime"
      //   ] = this.daterangeUpdataTime[0];
      //   this.queryParams.params["endUpdataTime"] = this.daterangeUpdataTime[1];
      // }
      this.queryParams.userId = this.$store.state.user.id;
      listGoodsCollections(this.queryParams).then(response => {
        this.goodsList = response.rows;
        //处理已被删除的收藏商品
        this.goodsList.forEach((item, index) => {
          if (!item.goodsName) {
            item.goodsName = "商品已卖出";
          }
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        typeId: null,
        "sysType.typeName": null,
        goodsName: null,
        goodDescription: null,
        goodsPrice: null,
        picture: null,
        goodsStatus: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updataBy: null,
        updataTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdataTime = [];
      this.queryParams["sysType.typeName"] = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品管理";
    },
    /** 商品已卖出按钮操作 */
    handleSell(row) {
      this.form.goodsId = row.goodsId;
      this.form.goodsStatus = 2;
      updateGoods(this.form).then(response => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const goodsId = row.goodsId || this.ids;
      getGoods(goodsId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.goodsId != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.createBy = this.$store.state.user.name;
            this.form.goodsStatus = 0;
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsId = row.goodsId;
      this.$modal
        .confirm('是否确认取消收藏编号为"' + goodsId + '"的商品？')
        .then(() => {
          return cancelCollection({
            userId: this.$store.state.user.id,
            goodsId: goodsId
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("已取消收藏");
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 批量取消收藏按钮
    handleDeleteList() {
      const goodsIds = this.ids;
      this.$modal
        .confirm('是否确认取消收藏编号为"' + goodsIds + '"的商品？')
        .then(() => {
          return cancelCollectionList({
            userId: this.$store.state.user.id,
            goodsIds: goodsIds
          });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("已取消收藏");
        })
        .catch(err => {
          console.log(err);
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "mysystem/goods/export",
        {
          ...this.queryParams
        },
        `goods_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
